const express = require('express');
const router = express.Router();
let db = require("../db.js");


//------        新增   ----------   
router.post("/add", function (req, res) {
  // 2.1  接受post数据  req.body 得到是对象
  console.log(req.body);

  // 2.2  数据库添加
  db("insert into category set ?", req.body, function (err, obj) {
    console.log(err);
    if (err != null) {
      res.send({
        status: 1,
        message: "新增计划失败！",
      });
    } else {
      res.send({
        status: 0,
        message: "新增计划成功！"
      });
    }
  });
});



// -----------------    列表   ------------------
router.get("/list", function (req, res) {
  db("select * from category", null, function (err, arr) {
    if (err != null) {
      res.send({
        status: 1,
        message: "获取计划列表失败！",
      });
    } else {
      res.send({
        status: 0,
        message: "获取计划列表成功！",
        arr: arr
      });
    }
  });
});


// ----------      删除     ---------------
router.get("/del/:id", function (req, res) {
  let id = req.params.id;

  db("delete from category where id=?", id, function (err, obj) {
    if (err != null) {
      res.send({
        status: 1,
        message: "删除计划失败！",
      });
    } else {
      res.send({
        status: 0,
        message: "删除计划成功！"
      });
    }
  });
});

// 3.更新：
router.post("/edit", function (req, res) {
  // 2.1  接受post数据  req.body 得到是对象
  // req.body {id,data,content}

  // 2.2  修改
  db("update category set ? where id=?", [req.body, req.body.id], function (err, obj) {
    if (err != null) {
      res.send({
        status: 1,
        message: "修改计划失败！",
      });
    } else {
      res.send({
        status: 0,
        message: "修改计划成功！"
      });
    }
  });
});


module.exports = router;